package com.zdkj.subway.check.util;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.Date;

/**
 * 自动补齐非空字段但是该值还是为null的
 */
public class ObejctFieldsValueNotNull {

    public static Object setValueNoNull(Class cla,Object object) throws IllegalAccessException, InstantiationException {
        Field[] declaredFields = cla.getDeclaredFields();
        for(Field f:declaredFields){
            String name = f.getName();
            JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(object));
            f.setAccessible(true);
            Class<?> type = f.getType();
            if(f.get(object)==null){
                setValue(type, f, object);
            }else{

            }
        }
        BeanUtils.copyProperties(object,object);
        return object;
    }

   private static String setValue(Class<?> type,Field f,Object o) throws IllegalAccessException {
        if(type.getName().endsWith("Integer")){
            f.set(o,0);
        }else if(type.getName().endsWith("Long")){
            f.set(o,0);
        }else if(type.getName().endsWith("Double")){
            f.set(o,0);
        }else if(type.getName().endsWith("String")){
            f.set(o,"");
        }else if(type.getName().endsWith("Timestamp")){
            f.set(o,new Timestamp(System.currentTimeMillis()));
        }else if(type.getName().endsWith("Date")){
            f.set(o,new Date());
        }else if(type.getName().endsWith("Boolean")){
            f.set(o,true);
        }else if(type.getName().endsWith("BigDecimal")){
            f.set(o,new BigDecimal(0));
        }
        return "";
    }

    /**
     * 乘多少数
     * @param cla
     * @param object
     * @return
     * @throws IllegalAccessException
     */
    public static Object jisuanBigDicmalMulti(Class cla,Object object,Double d) throws IllegalAccessException {
        Field[] declaredFields = cla.getDeclaredFields();
        for(Field f:declaredFields){
            f.setAccessible(true);
            Class<?> type = f.getType();
            if(type.getName().endsWith("BigDecimal") && f.get(object)!=null){
                BigDecimal b = (BigDecimal)f.get(object);
                f.set(object,b.multiply(new BigDecimal(d)));
            }
        }
       return object;
    }
}
